package com.AnywheeBt;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.AttributedCharacterIterator.Attribute;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadsetClient;
import android.bluetooth.BluetoothHeadsetClientCall;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothAvrcpController;
import android.bluetooth.BluetoothAvrcp;

/*
 * BtCallBack
 */
public class BtCallBack extends Activity {
	private static final String TAG = "BtCallBack";
	public static boolean bBtCallPhone = false;
	//*public native int WrtieUart(String cmd, int len, int delay);
	private TextView BtTextNumber = null;
	private TextView BtTextName = null;
	private TextView BtDial = null;
	private ImageButton BtCallChangeAudio = null;
	private ImageButton BtCannel = null;
	private View BtCallVolumeUp = null;
	private View BtCallVolumeDown = null;
	private View BtCallVolumeMute = null;
	private View BtCallVolumeHandsFree = null;
	private View BtCallVolumeConvertvoice = null;
	private View BtCallVolumeTransparency = null;
	public static int oneshot = 0;
	private BroadcastMain receiver = null;
	private int mCallStat = -1 ;
	private final static int UPDATE_TIME = 0;
	private int mCurrentTime = 0;
	private  AudioManager mAudioManager = null;
	private int maxVolume = 0;
	private int currentVolume = 0;
	private DatabaseHelper mDatabaseHelper = null; 
    private int mbtAudioStat = 1;  
	 
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case UPDATE_TIME:
                updateTime();
                break;

            default:
                break;
            }
        }
    };
	
    //
    private void updateTime() {
        String time = "";
        int h = mCurrentTime / 3600;
        int m = mCurrentTime % 3600 / 60;
        int s = mCurrentTime % 60;
        time = "" + (h > 9 ? h : "0" + h) + ":" + (m > 9 ? m : "0" + m) + ":"
                + (s > 9 ? s : "0" + s);
        BtDial.setText("" + time);
        mHandler.sendEmptyMessageDelayed(UPDATE_TIME, 1000);
        mCurrentTime++;
    }
    
    //
	public 	class BroadcastMain extends BroadcastReceiver {    
	    @Override  
	    public void onReceive(Context context, Intent intent) { 
    		String action = intent.getAction();
			if(action.equals("com.rk.bt.callStatchange")){
				mCallStat = intent.getExtras().getInt("callStat");
				if(mCallStat == BluetoothHeadsetClientCall.CALL_STATE_ACTIVE){
					updateTime();
				}else if(mCallStat == BluetoothHeadsetClientCall.CALL_STATE_INCOMING){
				}else if(mCallStat == BluetoothHeadsetClientCall.CALL_STATE_TERMINATED){
    				finish(); 
				}
			}
	    } 
	}
	
    @Override
	protected void onDestroy() {
        Log.i(TAG,"onDestroy");	 
        oneshot = 0;
    	super.onDestroy();
    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bt_view);
		
		receiver = new BroadcastMain();
		IntentFilter filter = new IntentFilter();
        filter.addAction("com.rk.bt.callStatchange");
        getApplicationContext().registerReceiver(receiver, filter);
		
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_BLUETOOTH_SCO);
		currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO);
		
        mDatabaseHelper = DatabaseHelper.getDatabaseHelper(this);
		oneshot = 1;
		Log.e(TAG, ">>>>>>>>>>>>>>>>onCreate<<<<<<<<<<<<<");
		BtCallVolumeTransparency = (View)this.findViewById(R.id.bt_call_volume_transparency);
		BtCallVolumeConvertvoice = (View)this.findViewById(R.id.bt_call_volume_convertvoice);
		BtCallVolumeHandsFree = (View)this.findViewById(R.id.bt_call_volume_handsfree);
		BtCallVolumeMute = (View)this.findViewById(R.id.bt_call_volume_mute);
		BtCallVolumeDown = (View)this.findViewById(R.id.bt_call_volume_down);
		BtCallVolumeUp = (View)this.findViewById(R.id.bt_call_volume_up);
		BtDial = (TextView)this.findViewById(R.id.bt_dial);
		BtTextNumber = (TextView)this.findViewById(R.id.bt_text);
		BtTextName = (TextView)this.findViewById(R.id.bt_name);
		BtCallChangeAudio = (ImageButton)this.findViewById(R.id.bt_change_audio);
		BtCannel = (ImageButton)this.findViewById(R.id.bt_cannel);
		
		Intent intent=getIntent();  
        Bundle bundle=intent.getExtras();  
        String str=bundle.getString("strNumber");
        bBtCallPhone = bundle.getBoolean("isDialout");
        BtTextNumber.setText(str);
		if (false == bBtCallPhone) {
			Log.e(TAG, ">>>>>>>>>>>>>>>>if<<<<<<<<<<<<<");
			//*BtDial.setBackgroundResource(R.drawable.bt_call_come);
			BtDial.setText(R.string.incoming_call);
		}else{
			//*BtOk.setBackgroundResource(R.drawable.bt_call_d);
		//	BtOk.setVisibility(View.GONE);
			BtDial.setText(R.string.outgoing_call);
			mCallStat = BluetoothHeadsetClientCall.CALL_STATE_DIALING;
		}
		SavePhone(str);
		
		BtCallChangeAudio.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.e("zcl", ">>>>>>>>>>>>>>>>BtOk<<<<<<<<<<<<<");
				if(mbtAudioStat == 0){
                    mbtAudioStat = 1;
                    SzhBAction.connectAudio();
                    Log.e("zcl", "mbtAudioStat = 0");
                }else if(mbtAudioStat == 1){
                     mbtAudioStat = 0;
                     SzhBAction.disConnectAudio();
                     Log.e("zcl", "mbtAudioStat = 1");
                }
			}
		});
		
		BtCannel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.e(TAG, ">>>>>>>>>>>>>>>>BtCannel<<<<<<<<<<<<<");
				onBackPressed();
				if(mCallStat < 0)
					return;
				if(mCallStat != BluetoothHeadsetClientCall.CALL_STATE_INCOMING)
					SzhBAction.terminateCall();
				else
					SzhBAction.hangupCall();
			}
		});
		
		BtCallVolumeTransparency.setOnClickListener(new OnClickListener() { 
			@Override
			public void onClick(View arg0) {
				Log.e(TAG, ">>>>>>>>>>>>>>>>BtCallVolumeTransparency<<<<<<<<<<<<<");
				Intent mIntent = new Intent(BtCallBack.this, PbList.class);
    			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    			startActivity(mIntent);
			}
		});
		
		BtCallVolumeConvertvoice.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log.e(TAG, ">>>>>>>>>>>>>>>>BtCallVolumeConvertvoice<<<<<<<<<<<<<");
				SzhBAction.SetCmdBt(SzhBAction.AT_CMD_CO, 0);
			}
		});
		
		BtCallVolumeHandsFree.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log.e(TAG, ">>>>>>>>>>>>>>>>BtCallVolumeHandsFree<<<<<<<<<<<<<");
				SzhBAction.SetCmdBt(SzhBAction.AT_INFO_MC, 0);
			}
		});
		
		BtCallVolumeMute.setOnClickListener(new OnClickListener() { 
			@Override
			public void onClick(View arg0) {
				Log.e(TAG, ">>>>>>>>>>>>>>>>BtCallVolumeMute<<<<<<<<<<<<<");
				SzhBAction.SetCmdBt(SzhBAction.AT_INFO_CM, 0);
			}
		});
		
		BtCallVolumeUp.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log.e(TAG, ">>>>>>>>>>>>>>>>BtCallVolumeUp<<<<<<<<<<<<<");
				            currentVolume ++;
			if(currentVolume <= maxVolume)
				mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, currentVolume, AudioManager.FLAG_SHOW_UI);
			else
				currentVolume = maxVolume;
			}
		});
		
		BtCallVolumeDown.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				            currentVolume --;
			if(currentVolume >= 0)
				mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, currentVolume, AudioManager.FLAG_SHOW_UI);
			else
				currentVolume = 0;
			}
		});
	}

	//
	private void SavePhone(String str) {
		if (str == "")
			return;
		Time time = new Time(); 
		time.setToNow();
		time.month = time.month + 1;
		String strTime = String.format("%02d-%02d %02d:%02d:%2d", time.month,
				time.monthDay, time.hour, time.minute, time.second);
		PbCallList pb_list = new PbCallList();
		pb_list.get_list(PbCallList.BT_PB_LIST);
		String strName = mDatabaseHelper.getNameByNum(str);

		if (strName != "" && this != null) 
			BtTextName.setText(strName);
	
		PbCallList call_list = new PbCallList();
		call_list.get_list(PbCallList.BT_CALL_LIST);
		call_list.SetList(strName, str, strTime, "" + bBtCallPhone, 0);
		call_list.Save_List(PbCallList.BT_CALL_LIST);
	}

	//
	public int SetCmdBt(String strCmd, int delay) {
		Log.e(TAG, ">>>>>>>>>>>SetCmdBt<<<<<<<<");
		int ret = -1;
		String StrCmd = String.format("AT#%s\r\n", strCmd);
		//*ret = WrtieUart(StrCmd, StrCmd.length(), delay);
		if (ret < 0)
			Toast.makeText(BtCallBack.this,getResources().getString(R.string.msg_connect_error),3).show();
		return ret;
	}
}
